<template>
  <section class="inputs">
    <div class="verificationCode">
      <input type="text" placeholder="请输入验证码" :value="modelValue" @input="inputType" :maxlength="max" />
      <button v-if="count > 0">已发送({{ count }})</button>
      <button v-else @click="getVerification">获取验证码</button>
    </div>
  </section>
</template>
<script>

import { defineComponent, ref } from 'vue';
import { getCode, } from '@/server/login'
import { ElMessage } from 'element-plus'
import { useRequest, useInterval, } from 'vue-hooks-plus'
export default defineComponent({
  props: {
    modelValue: {
      default: () => '',
      type: String
    },
    phone: {
      type: [String, Number],
      default: () => ""
    },
    max: {
      type: Number,
      default: () => 0
    },
    type: {
      type: Number,
      default: () => 0
    },
  },
  setup (props, { emit }) {
    const count = ref(0)
    //验证码
    const { run: getVerification } = useRequest(async () => {
      if (props.phone === '') return Promise.reject({
        type: "warning",
        msg: '请输入手机号'
      })
      return getCode({ phone: props.phone, type: props?.type })
    }, {
      manual: true,
      onSuccess: res => {
        if (res?.code === 500) {
          ElMessage({
            type: 'error',
            message: res?.msg,
            center: true,
          })
        } else {
          count.value = 60
          ElMessage({
            type: 'success',
            message: '验证码已发送',
            center: true,
          })
        }
      },
      onError: res => {
        ElMessage({
          type: res?.type,
          message: res?.msg,
          center: true
        })
      },
    })

    const inputType = (event) => {
      let value = event.target.value
      value = value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g, '')
      emit('update:modelValue', value)
    }

    useInterval(() => {
      count.value--
    }, count.value === 0 ? 1000 : undefined)

    return {
      getVerification,
      count,
      inputType
    }
  }
})
</script>

<style scoped lang="less">
.verificationCode {
  width: 100%;
  display: flex;
  width: 300px;
  height: 48px;
  margin-top: 12px;

  >input {
    width: 160px;
    height: 100%;
    background: #F4F4F4;
    border-radius: 6px;
    font-size: 16px;

    font-weight: 400;
    color: #787878;
    padding-left: 12px;
    border: none;
    outline: none;
  }

  >button {
    flex-shrink: 0;
    width: 130px;
    height: 48px;
    background: rgba(54, 207, 221, 0.1);
    border-radius: 6px;
    font-size: 16px;

    font-weight: 400;
    color: #01A0A0;
    border: none;
    cursor: pointer;
    margin-left: 10px;
  }
}
</style>
